package zkoran.qrfan;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Main activity which shows list of all matches and button to create new one
 * 
 * @author zdenda
 *
 */
public class QrFanActivity extends Activity {
	
	private static final int NEW_MATCH_REQUEST = 1;
	private static final int CONTEXTMENU_ADD = 0;
	private static final int CONTEXTMENU_DELETE = 1;
	
	private Button mButtonNew;
	private ListView mListViewMatches;
	
	private List<Match> mMatches = new ArrayList<Match>();
	private ArrayAdapter<Match> mAdapter;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        if(!MatchModel.isAvailable()) {
        	Toast.makeText(this, R.string.message_externaldirectory_error, Toast.LENGTH_LONG).show();
        	finish();
        }
        
        
        mButtonNew = (Button) findViewById(R.id.button_new_match);
        mButtonNew.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				startNewMatchActivity();				
			}
		});
        
        
        mListViewMatches = (ListView) findViewById(R.id.listView_matches);       
        
        mMatches.addAll(MatchModel.getAllMatches());
        mAdapter = new ArrayAdapter<Match>(this, android.R.layout.simple_list_item_1, mMatches);
        mListViewMatches.setAdapter(mAdapter);
        
        mListViewMatches.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position,	long id) {
				
				Intent intent = new Intent(getApplicationContext(), MatchActivity.class);
				intent.putExtra(MatchActivity.EXTRAS_NAME, ((TextView) view).getText());
				startActivity(intent);
				
			}
		});
        
        mListViewMatches.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				menu.setHeaderTitle(R.string.contextMenu_match_header);
				menu.add(Menu.NONE, CONTEXTMENU_ADD, Menu.NONE, R.string.contextMenu_match_add);
				menu.add(Menu.NONE, CONTEXTMENU_DELETE, Menu.NONE, R.string.contextMenu_match_delete);
				
			}
		});
        
    }
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	
    	// If the request went OK and the request was NEW_MATCH_REQUEST
    	if(resultCode == RESULT_OK && requestCode == NEW_MATCH_REQUEST) {
    		Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
    		refreshListViewMatches();
    		
    	}
    	
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.qrfan_menu, menu);
    	return true;
    }
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case R.id.menu_about:
			showDialogAbout();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
    }
    
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	
    	AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo();
    	String name = mMatches.get(menuInfo.position).toString();
    	
    	switch (item.getItemId()) {
		case CONTEXTMENU_DELETE:
			showDialogYesNo(name);
			break;

		case CONTEXTMENU_ADD:
			Intent intent = new Intent(getApplicationContext(), MatchActivity.class);
			intent.putExtra(MatchActivity.EXTRAS_NAME, name);
			startActivity(intent);
			break;
			
		default:
			break;
		}
    	
    	return super.onContextItemSelected(item);
    }


	/**
     * starts new activity {@link NewMatchActivity}
     */
	protected void startNewMatchActivity() {
		Intent intent = new Intent(this, NewMatchActivity.class);
		startActivityForResult(intent, NEW_MATCH_REQUEST);		
	}
	
	
	private void showDialogYesNo(final String name) {
				
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.alert_dialog_match_delete_title) + " " + name + " ?")
		       .setCancelable(false)
		       .setPositiveButton(R.string.alert_dialog_positive, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   MatchModel.deleteMatch(name);
		        	   refreshListViewMatches();
		           }
		       })
		       .setNegativeButton(R.string.alert_dialog_negative, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		
		AlertDialog alert = builder.create();
		alert.show();
		
	}
	
	
	private void showDialogAbout() {
		
		String version;
		try {
			version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			version = "-";
		}
		
		String text = String.format(getString(R.string.alert_dialog_about_message), version);		
		SpannableString message = new SpannableString(Html.fromHtml(text));
		Linkify.addLinks(message, Linkify.ALL);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.alert_dialog_about_title)
			.setMessage(message)
		    .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	   dialog.dismiss();
	           }
		    });
		
		AlertDialog alert = builder.create();
		alert.show();
		((TextView)alert.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
	}
	
	
	/**
	 * Loads fresh data and notifies listView to refreshing
	 */
	private void refreshListViewMatches() {
		
    	mMatches.clear();
		mMatches.addAll(MatchModel.getAllMatches());
		mAdapter.notifyDataSetChanged();
		
	}
    
}